package elka.sag.logisticsystem.actor;

import java.util.List;

import org.apache.log4j.Logger;

import elka.sag.logisticsystem.bean.ActionStatus;
import elka.sag.logisticsystem.bean.Article;
import elka.sag.logisticsystem.bean.Order;
import elka.sag.logisticsystem.bean.Order.OrderStatus;
import elka.sag.logisticsystem.message.SimpleMessage;

public class VerifyActor extends BaseActor {
	private final static Logger LOGGER = Logger.getLogger(VerifyActor.class);
	
	@Override
	protected void processMessage(SimpleMessage message) throws Exception {
		//dla symulacji przetwarzania czekamy przez losowy czas 0-10s
		int waitForTime = (int) (Math.random() * 1500);
		Thread.sleep(waitForTime);
		
		LOGGER.info("Weryfikacja zamowienia, orderId: " + message.getOrderId());
		Order order = repositoryService.getOrderById(message.getOrderId());
		ActionStatus actionStatus = ActionStatus.OK;
		
		//czy zamowienia ma towary
		List<Article> articles = repositoryService.getOrderArticles(order.getId());
		if(articles == null || articles.isEmpty()) {
			actionStatus = actionStatus.ERROR;
			order.setLastActionComment("Zamowienie nie posiada towarow");
		}
		
		OrderStatus newStatus = getNextOrderStatus(order, actionStatus);
		order.setStatus(newStatus);
		order.setProcess(false);
		
		//tylko zmiana statusu
		repositoryService.updateOrderStatusAndProcess(order);
	}

}
